<?php

class LedgersController extends AppController {

	public function index( $page = null ) {
		
		$this->pageTitle = 'Ledger Listing';
		
		$running_balance = 0;
		
		function updatebalance(&$value, $key) {
			global $running_balance;
					
			if ( $value['Ledger']['type'] == 'D') {
				$running_balance = $running_balance - $value['Ledger']['amount'];
			} elseif ( $value['Ledger']['type'] == 'C' ) {
				$running_balance = $running_balance + $value['Ledger']['amount'];
			}
			
			$value['Ledger']['balance'] = $running_balance;
						
		}

		//This will setup default query conditions
		$conditions = array(
				'contain' => false,
    			'order' => array('entry_date ASC', 'Ledger.id ASC')
    	);

		//This will get current user 
		$curruser = $this->Session->read('User');

		//If not a superuser, listing will only be for his organization
		if ( $curruser['User']['access_level'] > 0 ) {
			//$conditions['conditions'] = array('Organization.id' => $curruser['User']['organization_id']);
			$conditions['conditions']['Organization.id'] = $curruser['User']['organization_id'];
		}

		//If not an admin, listing will only be for his deparment and division		
		if ( $curruser['User']['access_level'] > 1 ) {
			$conditions['conditions']['Department.id'] = $curruser['User']['department_id'];
			$conditions['conditions']['Division.id'] = $curruser['User']['division_id'];
		}
		
		$conditions['conditions']['Ledger.status'] = 'A';


		$ledgers = $this->Ledger->find('all', 
			$conditions);
		
		array_walk($ledgers, "updatebalance");
		
		$page_offset 	= 25;
		$page_numbr 	= ($page == null ? 1 : $page);
		$page_total 	= ( count($ledgers) ) / $page_offset;

		if ( $page_numbr <= $page_total ) {
			$ledgers = array_slice($ledgers, -($page_numbr * $page_offset), $page_offset);
			
		} else {
			$ledgers = array_slice($ledgers, -($page_numbr * $page_offset), $page_offset - (($page_numbr * $page_offset) - count($ledgers)));

		}
		
		$pages['current'] = $page_numbr;
		$pages['total'] = ceil($page_total);
		$pages['linked_page'] = array(
									'controller' => 'ledgers', 
									'action' => 'index'
									);
		$filter = 1;
		$sidebarRight = 1;
		$this->set('pages', $pages);
		$this->set('filter', $filter);
		$this->set('sidebarRight', $sidebarRight);		
		$this->set('ledgers', $ledgers);
				
	}
	
	public function add() {
	
		$user = $this->Session->read('User');

		$organizations = $this->Ledger->Organization->find('list');
		$divisions = $this->Ledger->Division->find('list', array('conditions' => array('Division.status' => 'A', 'organization_id' => $user['User']['organization_id'])));
		$departments = $this->Ledger->Department->find('list', array('conditions' => array('Department.status' => 'A', 'organization_id' => $user['User']['organization_id'])));	
		$categories = $this->Ledger->Category->find('list', array('conditions' => array('Category.status' => 'A', 'organization_id' => $user['User']['organization_id'])));
	
			if ( $this->request->is('post') ) {

				$this->Ledger->set('organization_id', $user['User']['organization_id']);
			
				if ($this->Ledger->Division->id == '') {
					$this->Ledger->set('division_id', $user['User']['division_id']);
				}
				if ($this->Ledger->Department->id == '') {
					$this->Ledger->set('department_id', $user['User']['department_id']);
				}

				$this->Ledger->set('user_id', $user['User']['id']);
				
				$amount = $this->request->data['Ledger']['amount'];
				$amount = str_replace(",", "", $amount);
				$this->request->data['Ledger']['amount'] = floatval( $amount );
				
				if	($this->Ledger->save( $this->request->data ) ) {
						
					$this->redirect('/ledgers');
				}

			}
	
		$this->set('organizations', $organizations);
		$this->set('divisions',	$divisions);
		$this->set('departments', $departments);
		$this->set('categories', $categories);
	
	}
	
	public function edit($id = null) {
	
		$user = $this->Session->read('User');

		$organizations = $this->Ledger->Organization->find('list');
		$divisions = $this->Ledger->Division->find('list', array('conditions' => array('Division.status' => 'A', 'organization_id' => $user['User']['organization_id'])));
		$departments = $this->Ledger->Department->find('list', array('conditions' => array('Department.status' => 'A', 'organization_id' => $user['User']['organization_id'])));	
		$categories = $this->Ledger->Category->find('list', array('conditions' => array('Category.status' => 'A', 'organization_id' => $user['User']['organization_id'])));
	
	    if ( empty($this->request->data) ) {
			$this->request->data = $this->Ledger->findById($id);
			
			$e_date = $this->request->data['Ledger']['entry_date'];
			$e_date = substr($e_date, 5,2) . '/' . substr($e_date, 8,2) . '/' . substr($e_date, 0,4);
			
		} else {
		
				$this->Ledger->set('id', $id);
		
				$this->Ledger->set('organization_id', $user['User']['organization_id']);
			
				if ($this->Ledger->Division->id == '') {
					$this->Ledger->set('division_id', $user['User']['division_id']);
				}
				if ($this->Ledger->Department->id == '') {
					$this->Ledger->set('department_id', $user['User']['department_id']);
				}

				$this->Ledger->set('user_id', $user['User']['id']);
				
				$amount = $this->request->data['Ledger']['amount'];
				$amount = str_replace(",", "", $amount);
				$this->request->data['Ledger']['amount'] = floatval( $amount );
			
				if	($this->Ledger->save( $this->request->data ) ) {
					//audit trail
					$this->request->data['AuditTrail']['record_type'] = 'LEDGER';
					$this->request->data['AuditTrail']['action_type'] = 'EDIT';
					$this->request->data['AuditTrail']['record_id'] = $id;
					$this->request->data['AuditTrail']['user_id'] = $user['User']['id'];
					$this->request->data['AuditTrail']['detail'] = $this->request->data['Ledger']['detail'];
				
					$this->loadModel('AuditTrail');
					$this->AuditTrail->create();
					$this->AuditTrail->save( $this->request->data );
				
					$this->redirect('/ledgers');

				}
		}
				
		$this->set('eDate', $e_date);
		$this->set('organizations', $organizations);
		$this->set('divisions',	$divisions);
		$this->set('departments', $departments);
		$this->set('categories', $categories);
		$this->set('dType', $this->request->data['Ledger']['type']);
	
	}
	
	public function delete($id = null) {
	
		$organizations = $this->Ledger->Organization->find('list');
		$divisions = $this->Ledger->Division->find('list');
		$departments = $this->Ledger->Department->find('list');
		$categories = $this->Ledger->Category->find('list');

	
		if ( empty($this->request->data) ) {
			$this->request->data = $this->Ledger->findById($id);
			
		} else {
		
				$this->Ledger->set('id', $id);
				$this->Ledger->set('status', 'D');

				$this->Ledger->save( $this->request->data );

				//audit trail
				$user = $this->Session->read('User');
				$this->request->data['AuditTrail']['record_type'] = 'LEDGER';
				$this->request->data['AuditTrail']['action_type'] = 'DELETE';
				$this->request->data['AuditTrail']['record_id'] = $id;
				$this->request->data['AuditTrail']['user_id'] = $user['User']['id'];
				$this->request->data['AuditTrail']['detail'] = $this->request->data['Ledger']['detail'];
				
				$this->loadModel('AuditTrail');
				$this->AuditTrail->create();
				$this->AuditTrail->save( $this->request->data );
				
				$this->redirect('/ledgers');
		}
		
		$this->set('organizations', $organizations);
		$this->set('divisions',	$divisions);
		$this->set('departments', $departments);
		$this->set('categories', $categories);
	
	}
	
	public function import_ledger() {
	
	}

	public function test() {
	
		$organizations = $this->Ledger->Organization->find('list');
		$divisions = $this->Ledger->Division->find('list');
		$departments = $this->Ledger->Department->find('list');
		$categories = $this->Ledger->Category->find('list');
	
			if ( $this->request->is('post') ) {
				$user = $this->Session->read('User');
				$this->Ledger->set('organization_id', $user['User']['organization_id']);
			
				if ($this->Ledger->Division->id == '') {
					$this->Ledger->set('division_id', $user['User']['division_id']);
				}
				if ($this->Ledger->Department->id == '') {
					$this->Ledger->set('department_id', $user['User']['department_id']);
				}

				$this->Ledger->set('user_id', $user['User']['id']);
			
				$this->Ledger->save( $this->request->data );
				$this->redirect('/ledgers');
			}
	
		$this->set('organizations', $organizations);
		$this->set('divisions',	$divisions);
		$this->set('departments', $departments);
		$this->set('categories', $categories);
	
	}
	
	public function export() {
    	// https://github.com/josegonzalez/cakephp-csvview
    	
    	//This will get current user 
		$curruser = $this->Session->read('User');

		//If not a superuser, listing will only be for his organization
		if ( $curruser['User']['access_level'] > 0 ) {
			//$conditions['conditions'] = array('Organization.id' => $curruser['User']['organization_id']);
			$conditions['conditions']['Organization.id'] = $curruser['User']['organization_id'];
		}

		//If not an admin, listing will only be for his deparment and division		
		if ( $curruser['User']['access_level'] > 1 ) {
			$conditions['conditions']['Department.id'] = $curruser['User']['department_id'];
			$conditions['conditions']['Division.id'] = $curruser['User']['division_id'];
		}
		
		$conditions['conditions']['Ledger.status'] = 'A';

		$ledgers = $this->Ledger->find('all', 
			$conditions);

    	//$ledgers = $this->Ledger->find('all');

    	$_serialize = 'ledgers';
    	$_header = array('Ledger ID', 'Date', 'Details', 'Type', 'Amount', 'Category', 'Division','Department');
    	$_extract = array('Ledger.id', 'Ledger.entry_date', 'Ledger.details', 'Ledger.type', 'Ledger.amount', 'Category.name', 'Division.name', 'Department.name');

		$this->response->download('blink-journal.csv'); // <= setting the file name
	    $this->viewClass = 'CsvView.Csv';
    	$this->set(compact('ledgers', '_serialize', '_header', '_extract'));
	}

	function beforeRender() {
		parent::beforeRender();
		$this->set('module', 'Journal');
	}
	
}

?>